%**************************************************************************
% DISE-ADR model
% Aneli Bongers and Jose L. Torres (2025)
% Paper: "ADR"
% File: dynadr.m
% Function dynamics
%**************************************************************************
function [f,varargout]  =   dynadr(x,v,i,Params,varargin);
nouextra=max(nargout)-1;
ninextra=max(nargin)-4;
%**************************************************************************
% States
%**************************************************************************
k       =   x(1);
s       =   x(2);
W       =   x(3);
Z       =   x(4);
F       =   x(5);
Welfare =   x(6);
%**************************************************************************
% Endogenous solutions
%*************************************************************************
srk=v(1);
srs=v(2);
bw =v(3);
bz =v(4);
bf =v(5);
%**************************************************************************
%Variables
%**************************************************************************
y=Params.a(i)*k^Params.alpha1*s^Params.alpha2*(Params.N(i))^(1-Params.alpha1-Params.alpha2);
cc=(1-srk-srs-Params.ni1*bw^2-Params.ni2*bz^2-Params.ni3*bf^2)*y;
S=Params.mu*s/Params.q(i);
D=W+Z+F;
destroyed=(1-Params.v)*Params.theta*D*s;
l=Params.m(i)*srs*y;
L=Params.mu*(1-Params.m(i))*srs*y/Params.eta;
XX=Params.theta*(1-Params.v)*D*S;

 switch ninextra
     case 1
         u=varargin{1};
         c=u(1);
     case 0
         c=cc;
 end

k_next=(1-Params.deltak)*k+srk*y;
s_next=(1-Params.deltas)*s+Params.q(i)*(1-Params.m(i))*srs*y-destroyed;
W_next=(1-Params.deltaw-Params.epsilonw-bw)*W-Params.theta*(D+(1-Params.v)*S)*W+Params.xi*Params.deltas*S;
Z_next=(1-Params.deltaz-Params.epsilonz-bz)*Z-Params.theta*(D+(1-Params.v)*S)*Z+Params.psi*L;
F_next=(1-Params.deltaf-bf)*F+(1+Params.nu1)*Params.phiw*Params.epsilonw*W+(1+Params.nu1)*Params.phiz*Params.epsilonz*Z+(1+Params.nu1)*Params.omega*L+(1+Params.nu1)*Params.gammas*XX+(1+Params.nu1)*Params.gammaw*Params.theta*D*W+(1+Params.nu1)*Params.gammaz*Params.theta*D*Z;
Welfare_next=Welfare-Params.N(i)*((((c/Params.N(i))^(1-Params.sigma)-1)/(1-Params.sigma)))/(1+Params.rho)^(i-1);

f=[k_next;s_next;W_next;Z_next;F_next;Welfare_next];

if nouextra == 1
     varargout{1}=cc;
end
